<?php


namespace catchAdmin\storehouse\controller;


use app\command\SyncGoods;
use catchAdmin\basics\model\Provider;
use catchAdmin\externalGoods\excel\tenantOrdersExport;
use catchAdmin\product\model\Pack;
use catchAdmin\product\model\Product;
use catchAdmin\stock\model\Pick;
use catchAdmin\storehouse\excl\ediWarehouseOutExport;
use catchAdmin\storehouse\excl\warehouseOutExport;
use catchAdmin\storehouse\model\Project;
use catchAdmin\storehouse\model\WarehouseOut as WarehouseOutModel;
use catchAdmin\storehouse\model\WarehouseOutSon as WarehouseOutSonModel;
use catcher\base\CatchController;
use catcher\base\CatchRequest as Request;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\library\excel\Excel;
use catcher\Utils;
use Dompdf\Dompdf;
use Dompdf\Options;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Picqer\Barcode\BarcodeGeneratorPNG;
use think\Exception;
use think\facade\Db;
use think\helper\Str;

class WarehouseOut extends CatchController
{
    protected $warehouseOut;

    public function __construct(WarehouseOutModel $warehouseOut)
    {
        $this->warehouseOut = $warehouseOut;
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(CatchAuth $auth)
    {
        $user = $auth->user();
        $project_name = request()->param('project_name');
        return CatchResponse::paginate($this->warehouseOut->getList($user['tenant_id'], $project_name, $user['id'], $user['position'], $user['type']));
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function create(CatchAuth $auth, Request $request)
    {
        $params = $request->param();
        $user = $auth->user();
        $params['tenant_id'] = $user['tenant_id'];
        $params ["project_id"]= ["202507081426507503", "202507081429173282"];
        $params['project_client'] = $params['project_id'][1];
        $params['project_id'] = $params['project_id'][0];
        if (!empty($params['ship_to_city'])) {
            $params['ship_to_city'] = json_encode($params['ship_to_city']);
        }
        if (!empty($params['shipper_city'])) {
            $params['shipper_city'] = json_encode($params['shipper_city']);
        }

        if (!empty($params['packing_box'])) {
            $params['packing_box'] = implode(',', $params['packing_box']);
        }
        $params['warehouse_out_id'] = $user['tenant_id'] . date('YmdHis');
        if (!empty($params['consignee_relation_name'])) {
            $params['ship_to'] = $params['consignee_relation_name'];
            $params['ship_to_name'] = (new Provider())->where([
                'account_name' => $params['consignee_relation_name'],
                'relation_phone' => $params['consignee_relation_phone'],
                'addr' => $params['consignee_addr']
            ])->value('relation_name') ?? '';
            $params['ship_to_phone'] = $params['consignee_relation_phone'];
            $params['ship_to_address'] = $params['consignee_addr'];
        }
        $pk = $this->warehouseOut->storeBy($params);
        $return = $this->warehouseOut->find($pk)->toArray();
        return CatchResponse::success($return, '新建成功');
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function update(Request $request)
    {
//        $params = $request->filterEmptyField()->param();
        $params = $request->param();
        $id = $params['id'];
        $params['project_client'] = $params['project_id'][1];
        $params['project_id'] = $params['project_id'][0];
        if (!empty($params['ship_to_city'])) {
            $params['ship_to_city'] = json_encode($params['ship_to_city']);
        }
        if (!empty($params['shipper_city'])) {
            $params['shipper_city'] = json_encode($params['shipper_city']);
        }
        if (!empty($params['packing_box'])) {
            $params['packing_box'] = implode(',', $params['packing_box']);
        } else {
            $params['packing_box'] = '';
        }
        $params['ship_to'] = $params['consignee_relation_name'];
        $params['ship_to_name'] = (new Provider())->where([
            'account_name' => $params['consignee_relation_name'],
            'relation_phone' => $params['consignee_relation_phone'],
            'addr' => $params['consignee_addr']
        ])->value('relation_name') ?? '';
        $params['ship_to_phone'] = $params['consignee_relation_phone'];
        $params['ship_to_address'] = $params['consignee_addr'];
        $this->warehouseOut->updateBy($id, $params);
        $return = $this->warehouseOut->find($id)->toArray();
        return CatchResponse::success($return, '编辑成功');
    }
    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
//    public function delete(Request $request)
//    {
//        $id = $request->post('id');
//        $ids = Utils::stringToArrayBy($id);
//        foreach ($ids as $_id) {
//            $this->warehouseOut->deleteBy($_id);
//        }
//        return CatchResponse::success('', '删除成功');
//    }

    public function delete(Request $request)
    {
        $id = $request->post('id');
        $id = is_array($id) ? $id : [$id];
        $warehouseOutSonModel = new WarehouseOutSonModel;

        Db::startTrans();
        try {
            foreach ($id as $value) {
                $warehouseOutModel = $this->warehouseOut->find($value);
                $warehouse_out_id = $warehouseOutModel->warehouse_out_id;

                //判断是否子单没有删除干净
                $warehouse_out_son_id = $warehouseOutSonModel
                    ->where('warehouse_out_id', $warehouse_out_id)
                    ->select()->toArray();

                if (!empty($warehouse_out_son_id)) {
                    Db::rollback();
                    throw new Exception('请先删除全部明细单');
                }
                $warehouseOutModel->delete();
            }
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('删除失败，' . $exception->getMessage());
        }
        return CatchResponse::success('', '删除成功');

    }


    public function exportData($id, Request $request)
    {

        return CatchResponse::success($this->warehouseOut->getExportData($id));
    }

    public function exportExcel($id, Request $request)
    {
        //$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('export/template/pickingList.xlsx');
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('export/template/pickingList11.xlsx');
        $worksheet = $spreadsheet->getActiveSheet();

//        //设置样式
//        $styleArray = [
//            'alignment' =>  [
//                'horizontal' =>  'center',  // 水平居中
//                'vertical' =>  'center',    // 垂直居中
//            ],
//            'font' =>  [
//                'name' =>  '宋体',
//                'bold' =>  true,
////                'size' =>  22,
//                'color'=>  [
//                    'rgb' => '993441'
//                ]
//            ]
//        ];
//        $worksheet->getStyle('C8:D8')->applyFromArray($styleArray);
//        $worksheet->getStyle('C9:D9')->applyFromArray($styleArray);

        $out_id = $id;

        $exportData = $this->warehouseOut->getExportData($out_id);

        if (empty($exportData['warehouseOutSon']) || empty($exportData['pick'])) {
            throw new Exception('无明细单、或无捡货列表');
        }

        //dd($exportData);

//        //后期做
//        if (file_exists('write.xlsx')) {
//            // 删除文件
//            unlink('write.xlsx');
//        }

        //1.设置客户代码 送货方客户代码
//        $account_code = $exportData['warehouseOut']['account_code'];
        $account_code = $exportData['warehouseOut']['shipper_serial_number'];
        $worksheet->setCellValue("B4", $account_code);

        //2.设置出库单号
        $warehouse_out_id = $exportData['warehouseOut']['warehouse_out_id'];
        $worksheet->setCellValue("B5", $warehouse_out_id);


        //设置 收货方客户代码
        $consignee_serial_number = $exportData['warehouseOut']['consignee_serial_number'];
        $worksheet->setCellValue("D4", $consignee_serial_number);

        //设置 客户业务单号
        $customer_business_number = $exportData['warehouseOut']['customer_business_number'];
        $worksheet->mergeCells("G5:H5");
        $worksheet->setCellValue("G5", $customer_business_number);

        //设置 order#
        $worksheet->mergeCells("K5:L5:M5");
        $worksheet->setCellValue("K5", '');


//        //3.设置 捡货单单号
//        $pick_no = $exportData['pick_no'];
//        $worksheet->setCellValue("G4",$pick_no);

        //3.设置 出库单号
        //$pick_no = $exportData['pick_no'];
        $worksheet->setCellValue("G4", '*' . $warehouse_out_id . "*");

        //4.明细单商品
        $warehouse_out_son = $exportData['warehouseOutSon'];
        if (0 < $warehouse_out_son_count = count($warehouse_out_son)) {

            if ($warehouse_out_son_count != 1) {
                $worksheet->insertNewRowBefore(9, $warehouse_out_son_count - 1);
            }
            //明细单数据
            $warehouse_out_son_excel = [];
            $warehouse_out_son_items = [];
            $_tray_num = 0;
            foreach ($warehouse_out_son as $key => &$value) {
                $value['item'] = $key + 1;
                $warehouse_out_son_items[$value['warehouse_out_son_id']]['id'] = $value['item'];
                $warehouse_out_son_excel_data = [];
//                $warehouse_out_son_excel_data[0] =  $value['serial_number'];
                $warehouse_out_son_excel_data[0] = $value['item'];
                $warehouse_out_son_excel_data[1] = date("Y/m/d", strtotime($value['created_at']));
                $warehouse_out_son_excel_data[2] = $value['goods_name'];
                $warehouse_out_son_excel_data[3] = '';
                $warehouse_out_son_excel_data[4] = $value['number'];
                $warehouse_out_son_excel_data[5] = $value['box_number'];
//                $warehouse_out_son_excel_data[6] = ''; //所需要托盘数总数
                $warehouse_out_son_excel_data[6] = ceil($value['box_number'] / $value['_layup_num']);    //所需要托盘数总数
                $_tray_num += $warehouse_out_son_excel_data[6];
//                $warehouse_out_son_excel_data[7] = '';
                $warehouse_out_son_excel_data[7] = $value['PO']; //PO
                $warehouse_out_son_excel_data[8] = '';
                $warehouse_out_son_excel_data[9] = $value['LOT1'];
                $warehouse_out_son_excel_data[10] = $value['LOT2'];
                $warehouse_out_son_excel_data[11] = '';
                $warehouse_out_son_excel_data[12] = $value['LOT3'];
                $warehouse_out_son_excel[] = $warehouse_out_son_excel_data;

                $current_line = 8 + $key;
                $worksheet->mergeCells("C{$current_line}:D{$current_line}");
                $worksheet->mergeCells("H{$current_line}:I{$current_line}");
                $worksheet->mergeCells("K{$current_line}:L{$current_line}");

//                $worksheet->setCellValue("J{$current_line}",'分配');
            }

            $worksheet->fromArray($warehouse_out_son_excel, null, "A8");

            //5。设置明细单总数 不用表格函数
            $warehouseOutSonTotalNumber = $exportData['warehouseOutSonTotalNumber'];
            $warehouseOutSonTotalBoxNumber = $exportData['warehouseOutSonTotalBoxNumber'];
            $warehouseOutSonTotalTrayNumber = $exportData['warehouseOutSonTotalBoxNumber'];
            $worksheet->setCellValue("E" . ++$current_line, $warehouseOutSonTotalNumber);
            $worksheet->setCellValue("F" . $current_line, $warehouseOutSonTotalBoxNumber);
            $worksheet->setCellValue("G" . $current_line, $_tray_num);
        }


        //6.设置捡获单。
        $pick_list = $exportData['pick'];
        if (0 < $pick_list_count = count($pick_list)) {
            $current_line += 3;
            $cur_line = $current_line;
//            dd($current_line);
            $worksheet->insertNewRowBefore($current_line, $pick_list_count);
            //明细单数据
            $pick_excel = [];

            $worksheet->mergeCells("D{$current_line}:E{$current_line}");
            $worksheet->mergeCells("I{$current_line}:J{$current_line}");
            $worksheet->mergeCells("K{$current_line}:L{$current_line}");


            $new_pick_list = [];
            foreach ($warehouse_out_son_items as $key1 => &$value1) {
                $new_pick_list = array_merge($new_pick_list, array_filter($pick_list, function ($item) use ($key1) {
                    return $item['warehouse_out_son_id'] == $key1;
                }));
            }

            $_item1 = 1;
            $_r = '';
            foreach ($new_pick_list as $key => $value) {

                if ($value['warehouse_out_son_id'] !== $_r) {//重置
                    $_r = $value['warehouse_out_son_id'];
                    $_item1 = 1;
                } else {
                    $_item1++;
                }

                $pick_data = [];
//                $pick_data[0] = '未查询';
                $_key1 = $key + 1;
                $pick_data[0] = $_key1 . "/" . $warehouse_out_son_items[$value['warehouse_out_son_id']]['id'] . '-' . $_item1;
                $pick_data[1] = $value['goods_name'];
                $pick_data[2] = $value['new_item_number'];//项号
                $pick_data[3] = $value['ing_customer_business_number'];//FCR
                $pick_data[4] = '';//FCR
                $pick_data[5] = $value['name'];
                $pick_data[6] = $value['number'];

                if ($value['status'] == 0) { // 未出库 出库要区分数据 防止出现负数
                    $pick_data[7] = (string)(array_sum([$value['_Good_Qty'], $value['_Hold_Qty'], $value['_NG_Qty']]) - (int)$value['number']);
                } else {
                    $pick_data[7] = (string)array_sum([$value['_Good_Qty'], $value['_Hold_Qty'], $value['_NG_Qty']]);
                }
                $pick_data[8] = $value['tray_id'];
                $pick_data[9] = '';
                $pick_data[10] = $value['box_id'];
                $pick_data[11] = '';
                $pick_data[12] = $value['slice_id'];
                $pick_data[13] = $value['LOT1'];
                $pick_data[14] = $value['LOT2'];
                $pick_data[15] = $value['LOT3'];

                $pick_excel[] = $pick_data;
                ++$current_line;
                $worksheet->mergeCells("D{$current_line}:E{$current_line}");
                $worksheet->mergeCells("I{$current_line}:J{$current_line}");
                $worksheet->mergeCells("K{$current_line}:L{$current_line}");

            }

            $worksheet->fromArray($pick_excel, null, "A{$cur_line}");

            //7.设置捡获总数量
            $pickTotalNumber = $exportData['pickTotalNumber'];
            $current_line = $current_line + 4;
            $worksheet->setCellValue("G" . $current_line, $pickTotalNumber);
        }

        $current_line = $current_line + 4;
        $pub_name = $exportData['warehouseOut']['pub_name'];
        $warehouse_out_date = date("Y/m/d", strtotime($exportData['warehouseOut']['created_at']));
        $worksheet->setCellValue("B" . $current_line, $pub_name);
        $worksheet->mergeCells("J{$current_line}:K{$current_line}:L{$current_line}");
        $worksheet->setCellValue("J{$current_line}", $warehouse_out_date);

        $current_line = $current_line + 1;
        $print_name = ((new CatchAuth())->user())['username'];
        $print_date = date("Y/m/d");
        $worksheet->setCellValue("B" . $current_line, $print_name);
        $worksheet->mergeCells("J{$current_line}:K{$current_line}:L{$current_line}");
//        $worksheet->mergeCells("K5:L5:M5");
        $worksheet->setCellValue("J{$current_line}", $print_date);


        $worksheet->mergeCells('G4:M4');//单元格合并

        //条形码输出
        /*

        $export_file_path = "export/" .  date('YmdHis').Str::random(6) ;
        $generator = new BarcodeGeneratorPNG();
        $redColor = [0, 0, 0];
        file_put_contents( $export_file_path . 'barcode.png', $generator->getBarcode($warehouse_out_id, $generator::TYPE_CODE_128, 3, 50, $redColor));

        $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
        $drawing->setWorksheet($worksheet);
        $drawing->setPath($export_file_path . 'barcode.png');
        $drawing->setWidth(360);//图片宽
        $drawing->setHeight(30);//图片高
//$drawing->setOffsetX(100);//设置图片偏移量
        $drawing->setCoordinates('G4');//将图片放置于单元格

        */

        //导出
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $file = "export/" . date('YmdHis') . Str::random(6) . "_picking_list.xlsx";
//        $file =  $export_file_path  . "_picking_list.xlsx";
        $writer->save($file);

        return CatchResponse::success([
//            'url'=>"http://192.168.31.168:8000" . '/' .  $file
//            'url'=>"http://192.168.1.8:8000" . '/' .  $file
            'url' => "http://cross.qekj.net" . '/' . $file
        ]);
    }

    public function exportDeliver($id, Request $request)
    {
        $out_id = $id;

        $exportData = $this->warehouseOut->getExportData($out_id);

        if (empty($exportData['warehouseOutSon']) || empty($exportData['pick'])) {
            throw new Exception('无明细单、或无捡货列表');
        }

        //2.设置出库单号
        $warehouse_out_id = $exportData['warehouseOut']['warehouse_out_id'];

        // 运单号
        $waybill_no = $exportData['warehouseOut']['waybill'];
        if (empty($waybill_no)) {
            $waybill_no = $warehouse_out_id;
        }
        //打印时间 Y-m-d H:i:s
        $print_date = date("Y-m-d H:i:s");

        $options = new Options();

        $options->set('defaultFont', 'SimSun'); // 设置默认字体（可选）
//        $options->set("isHtml5ParserEnabled", true);
//        $options->set("isPhpEnabled", true);
        $dompdf = new Dompdf($options);

        $html = '';

        $aa = "&nbsp;&nbsp;&nbsp;&nbsp;";

        $export_file_path = "export/" . date('YmdHis') . Str::random(6);
        $generator = new BarcodeGeneratorPNG();
        $redColor = [0, 0, 0];
        file_put_contents($export_file_path . 'barcode.png', $generator->getBarcode($waybill_no, $generator::TYPE_CODE_128, 3, 50, $redColor));

        $linecode = base64_encode(file_get_contents($export_file_path . 'barcode.png'));
        $linecode = 'data:image/png;base64,' . $linecode;

        $table_body = '';
        foreach ($exportData['pick'] as $key => $value) {

            $export_file_path = "export/" . date('YmdHis') . Str::random(6);
            file_put_contents($export_file_path . 'barcode.png', $generator->getBarcode($value['goods_name'], $generator::TYPE_CODE_128, 3, 50, $redColor));

            $linecode_goods = base64_encode(file_get_contents($export_file_path . 'barcode.png'));
            $linecode_goods = 'data:image/png;base64,' . $linecode_goods;

            $line = $key + 1;
            $table_body .= "<tr><td>{$line}</td> <td id='position'>{$value['name']}</td>
              <td id='product-name'>
              {$value['goods_Cname']}
              <div class='barcode'>
                  <img src='{$linecode_goods}' alt='条形码'>
                  <div class='barcode-number' >{$value['goods_name']}</div>
              </div>
              </td>
              <td id='quantity'>{$value['number']}</td>
              </tr>";
        }

        //发货数量合计
        $total_quantity = $exportData['warehouseOut']['goods_number'];

        /***
         *
         * //用QrCode生成二维码
         * $qrCode = new QrCode('https://www.example.com');  // 二维码内容
         * $qrCode->setSize(150);  // 设置二维码大小
         * $qrCode->setMargin(3);  // 设置二维码的边距
         * $qrCode->setEncoding('UTF-8');  // 设置编码
         * //        $qrCode->setForegroundColor([0, 0, 0]);  // 设置二维码颜色（黑色）
         * //        $qrCode->setBackgroundColor([255, 255, 255]);  // 设置背景颜色（白色）
         *
         * // 获取二维码的Base64编码
         * $base64Image = base64_encode($qrCode->writeString());
         * // 返回Base64编码的二维码图片
         * $dataUri = 'data:image/png;base64,' . $base64Image;
         */

        $html .= <<<HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>发货清单</title>
    <style>
        @page {
            size: 10.5cm 18cm;
            margin: 0;
        }
        body {
            font-family: SimSun, "宋体", sans-serif;
            margin: 0.3cm;
            font-size: 12px;
            width: 9.9cm;
            height: 17.4cm;
        }
        .header {
            background-color: #ff6b6b;
            color: white;
            padding: 4px;
            text-align: center;
            font-size: 14px;
            margin-bottom: 6px;
        }
        .order-title {
            font-size: 13px;
            font-weight: bold;
            margin-bottom: 6px;
            text-align: center;
        }
        .info-row {
            margin-bottom: 3px;
            font-size: 12px;
            display: flex;
            justify-content: space-between;
        }
        .info-row span {
            flex: 1;
            text-align: left;
            margin-left: 5px;
        }
        .barcode {
            text-align: center;
            margin: 4px 0;
        }
        .barcode img {
            max-width: 90%;
            width: 40%;
            height: 20px;
        }
        .barcode-number {
            font-size: 11px;
            margin-top: 2px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 6px 0;
            font-size: 11px;
            border: 0.1px solid #000;
            table-layout: fixed;
        }
        table, th, td {
            border: 0.1px solid #000;
        }
        th, td {
            padding: 3px;
            text-align: center;
            word-wrap: break-word;
            word-break: break-all;
        }
        th:nth-child(1), td:nth-child(1) {
            width: 15%;
        }
        th:nth-child(2), td:nth-child(2) {
            width: 20%;
        }
        th:nth-child(3), td:nth-child(3) {
            width: 50%;
        }
        th:nth-child(4), td:nth-child(4) {
            width: 15%;
        }
        th {
            /* background-color: #f5f5f5; */
        }
        .total {
            margin: 4px 0;
            font-size: 12px;
            text-align: left;
        }
        .remarks {
            margin-top: 6px;
            font-size: 11px;
        }
        .remarks div {
            margin-bottom: 2px;
        }
        .address-row {
            margin: 4px 0;
            font-size: 11px;
        }
    </style>
</head>
<body>
    <div class="header">发货清单</div>
    
    <div class="order-title">订单发货明细</div>
    
    <div class="info-row">
        <label>收货人：</label><span id="receiver"></span>
    </div>
    <div class="info-row">
        <label>收货人手机：</label><span id="phone"></span>
    </div>
    <div class="info-row">
        <label>打印时间：</label><span id="print-time">{$print_date}</span>
    </div>
    
    <div class="barcode">
        <img src="{$linecode}" alt="条形码">
        <div class="barcode-number">{$waybill_no}</div>
    </div>
    
    <div class="info-row">
        <label>物流公司：</label><span id="logistics"></span>
    </div>
    
    <table>
        <thead>
            <tr>
                <th>行号</th>
                <th>商品货位</th>
                <th>商品简名</th>
                <th>数量</th>
            </tr>
        </thead>
        <tbody>
            {$table_body}
        </tbody>
    </table>
    
    <div class="total">发货数量合计：<span id="total-quantity">{$total_quantity}</span></div>
    
    <div class="address-row">收货地址：<span id="address"></span></div>
    
    <div class="remarks">
        <div>买家留言：<span id="buyer-message"></span></div>
        <div>卖家备注：<span id="buyer-note"></span></div>
        <div>卖家网店名称：<span id="shop-name"></span></div>
        <div>业务员：<span id="sales"></span></div>
    </div>
</body>
</html>



HTML;

        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $output = $dompdf->output();


        $file = "export/" . date('YmdHis') . Str::random(6) . "_deliver_list.pdf";

        if (file_put_contents($file, $output) === false) {
            throw new Exception('无法写入 PDF 文件到指定路径！');
        }

        return CatchResponse::success([
            //  'url'=>"http://192.168.31.168:8000" . '/' .  $file
//            'url'=>"http://192.168.1.8:8000" . '/' .  $file
            'url' => "http://cross.qekj.net" . '/' . $file
        ]);
    }


    //佳壹物流销售发货单
    public function exportPDF($id, Request $request)
    {
        $warehouseOutInfo = $this->warehouseOut->findBy($id);

        if (empty($warehouseOutInfo['edi_json'])) {
            return CatchResponse::fail('非EDI订单，不支持生成该发货单');
        }

        if ($warehouseOutInfo['status'] != 1) {
            return CatchResponse::fail('该订单未全部出库');
        }

        $customer_business_number = $warehouseOutInfo['customer_business_number'];

        // 创建一个 dompdf 对象
        $options = new Options();

        //        php load_font.php SimSun  SimSun.ttf
        $options->set('defaultFont', 'simsun'); // 设置默认字体（可选）

        $dompdf = new Dompdf($options);
        // 将 HTML 添加到 dompdf
        $html = '';

        $wareHouseOutModel = new WarehouseOutModel;
        $warehouseOutResult = $wareHouseOutModel->where(['customer_business_number' => $customer_business_number])->find()->toArray();

        $edi_json = json_decode($warehouseOutResult['edi_json'], true);

        $warehouseOutNO = $warehouseOutResult['customer_business_number'];//发货单号

        $warehouseOutDate = date("Y-m-d", strtotime($warehouseOutResult['updated_at']));//发货日期

        $providerModel = new Provider;

        $customerCode = $edi_json[0][9];//客户代码

        $customerName = $providerModel->where('account_code', $customerCode)->value('account_name');//客户名称
//        $customerCode = $edi_json[0][6];//收货方代码
//        $receiveName =  $providerModel->where('account_code',$customerCode)->value('account_name');//收货方名称

        $receiveName = $edi_json[0][19];//收货方简称
        $receiveAddress = $edi_json[0][20];//收货方地址
        $receivePerson = $edi_json[0][24];//收货方联系人
        $receivePhone = $edi_json[0][22];//收货方联系电话

        //承运人
        $carrierCode = $edi_json[0][7];//承运方代码
        $carrierName = $providerModel->where('account_code', $carrierCode)->value('account_name');//承运方名称


        $carrierType = $edi_json[0][13];//承运方式
        $carrierTypeOptions = [
            '01' => 'Truck',
            '02' => 'Mail',
            '03' => 'Rail',
            '04' => 'Sea',
            'Z1' => 'Air',
            'Z2' => 'Courier',
            'Z3' => 'Road',
            'Z4' => 'Pick up',
            'Z5' => 'To be contacted',
            'Z6' => 'Door to door deliver',
            'Z7' => 'Package',
            'Z8' => 'Express',
            'Z9' => 'Road+Railway',
        ];

        $carrierType = array_key_exists($carrierType, $carrierTypeOptions) ? $carrierTypeOptions[$carrierType] : 'Other';

        if ($warehouseOutResult['project_client'] == '202406261542166632') {//西安
            $deliveryWarehouse = '陕西省西安市幸福南路61号';
        } else {//成都
            $deliveryWarehouse = '四川成都市双流区通关路86号';
        }

//        dd($warehouseResult);

//        var_dump($edi_json);die();

        $edi_length = count($edi_json);

//        $edi_json = array_merge($edi_json,$edi_json);

        $totalNum = (int)array_sum(array_column($edi_json, 58));

        $edi_json[] = [];
        $groupArray = array_chunk($edi_json, 10);

        $pages = count($groupArray);
        $productModel = new Product;

        $logosrc = app()->getRootPath() . 'public/mnd.png';

        // 从远程 URL 获取图片内容并编码为 Base64
        $imageData = base64_encode(file_get_contents('http://cross.qekj.net/mnd.jpeg'));
        $imageBase64 = 'data:image/jpeg;base64,' . $imageData;


        $khzfyf = $edi_json[0][41];//客户支付运费
        $dhrqsj = $edi_json[0][27];//到货日期时间
        $drlxrdh = $edi_json[0][28];//当日联系人及电话
        $lcs = $edi_json[0][34];//楼层数
        $sfyht = $edi_json[0][35];//是否有货梯
        $tcccgxz = $edi_json[0][32];//停车场车高限制
        $xyyhdwp = $edi_json[0][38];//需要运回的物品:
        $ltgdhsl = $edi_json[0][36];//楼梯高度及数量
        $sfxyxckc = $edi_json[0][39];//是否需要现场勘查
        $jmkkd = $edi_json[0][37];//进门口宽度
        $whrysfyqdxc = $edi_json[0][30];//维护人员是否一起到现场
        $khddmc = $edi_json[0][29];//客户担当名称
        $sfzt = $edi_json[0][40];//是否自提

        $remark = $edi_json[0][14];


        //print_r($imageBase64);

        //print_r($logosrc);

        //dd($edi_json);
        for ($i = 0; $i < $pages; $i++) {
            $html .= <<<HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>发货单</title>
  <style>
    body {
      font-family: simsun;
      line-height: 1;
      font-size: 12px;
    }
    .header {
      text-align: center;
      margin-bottom: 10px;
    }
    .info {
      margin-bottom: 10px;
      clear: both; /* 清除浮动 */
    }
    .left {
      width: 40%;
      float: left;
    }
    .right {
      width: 60%;
      float: right;
      text-align: right;
    }
    .right p:first-child{
      float: left;
    }
    .info p {
      margin: 5px 0; /* 调整段落的上下边距 */
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }
    /*table, th, td {*/
    th, td {
      border: 0.5px solid black;
      padding: 2px;
      text-align: center;
    }
    table.t1 th, table.t1 td {
      border:none;
    }
    table.t1 td{
      padding: 5px 0;
    }
    th {
      /*background-color: #f2f2f2;*/
    }
    .ddd div{
      padding: 10px 0;
      clear: both; /* 清除浮动 */
    }
    .ddd div:before{
      content: '';
      display: none;
      width: 12px;
      height: 12px;
      border: 0.5px solid #000;
      float: left;
      /*margin: 0;*/
      padding: 0;
      margin-right: -12px; /* 调整打勾方框和文字之间的水平间距 */
      vertical-align: middle; /* 垂直居中对齐 */
    }
  </style>
</head>
<body>

<div class="header" style="width: 80%;height: 100px;line-height: 100px;margin: 0 auto;text-align: center;">
  <div style="float: left; width: 30%;height: 100%;text-align: left;">
<!--    <img style="height: 100%;" src="" alt=""/>-->
    <img src="{$imageBase64}"  style="height: 100%;">
  </div>
  <div style="width: 70%; vertical-align: middle; font-size: 22px;font-family: SimSun;float: left;height: 100px;line-height: 100px;">柯尼卡美能达办公系统（中国）有限公司发货单</div>
</div>
<div class="info">
  <div class="left">
    <p><strong>发货单号：</strong> {$warehouseOutNO}</p>
  </div>
  <div class="right">
    <p><strong>发货日期：</strong> {$warehouseOutDate}</p>
    <p><strong>订单创建人：</strong> EDI </p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>发货类型：</strong> </p>
  </div>
  <div class="right">
    <p><strong>订单类型：</strong> </p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>订单号：</strong> </p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>客户订单号：</strong> </p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>结算方：</strong> 发货仓库：{$deliveryWarehouse}</p>
  </div>
  <div class="right">
    <p><strong>客户名称：</strong> {$customerName}</p>
  </div>
</div>
<div class="info" style="margin: 0;">
  <div  style="margin: 0;">
    <p  style="margin: 0;"><strong>收货地址：</strong> {$receiveAddress}</p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>联系人：</strong> {$receivePerson}</p>
  </div>
  <div class="right">
    <p><strong>联系电话：</strong> {$receivePhone}</p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>承运人：</strong> {$carrierName}</p>
  </div>
  <div class="right">
    <p><strong>运输方式：</strong> {$carrierType}</p>
    <p><strong>{$khzfyf}</strong> </p>
  </div>
</div>

<div class="info">
  <div class="left">
    <p><strong>{$dhrqsj}</strong> </p>
  </div>
  <div class="right">
    <p><strong>备注：</strong> </p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>{$drlxrdh}</strong> </p>
  </div>
  <div class="right">
    <p><strong>{$lcs}</strong> </p>
  </div>
</div>

<div class="info">
  <div class="left">
    <p><strong>{$sfyht}</strong> </p>
  </div>
  <div class="right">
    <p><strong>{$tcccgxz}</strong> </p>
  </div>
</div>

<div class="info">
  <div class="left">
    <p><strong>{$xyyhdwp}</strong> </p>
  </div>
  <div class="right">
    <p><strong>{$ltgdhsl}</strong> </p>
  </div>
</div>

<div class="info">
  <div class="left">
    <p><strong>{$sfxyxckc}</strong> </p>
  </div>
  <div class="right">
    <p><strong>{$jmkkd}</strong> </p>
  </div>
</div>

<div class="info">
  <div class="left">
    <p><strong>{$whrysfyqdxc}</strong> </p>
  </div>
  <div class="right">
    <p><strong>{$khddmc}</strong> </p>
  </div>
</div>

<div class="info">
  <div class="left">
    <p><strong>{$sfzt}</strong> </p>
  </div>
</div>

<div class="info" style="margin: 0;">
  <div  style="margin: 0;">
    <p style="word-wrap: break-word;padding: 0;margin: 0;">  摘要： {$remark}</p>
  </div>
</div>

HTML;

            $html .= <<<HTML
<div style="height: 20%">
<table>
  <thead>
  <tr>
    <td>序号</td>
    <td>货物编号</td>
    <td>货物名称</td>
    <td>计量单位</td>
    <td>单价</td>
    <td>数量</td>
    <td>销售额</td>
  </tr>
HTML;

            $currentPageCont = count($groupArray[$i]);
            foreach ($groupArray[$i] as $key => $value) {


                if (($i + 1 == $pages) && ($key + 1 == $currentPageCont)) {//最后一个
                    $html .= <<<HTML
  <tr>
    <td style="border: 0 !important;"></td>
    <td style="border: 0 !important;"></td>
    <td style="border: 0 !important;"></td>
    <td style="border: 0 !important;"></td>
    <td></td>
    <td>{$totalNum}</td>
    <td style="border: 0 !important;"></td>
  </tr>

HTML;

                } else {
                    $goods_name = $productModel->where('goods_name', $value[56])->value('goods_Cname');

                    $html .= <<<HTML
  <tr>
    <td>{$value[50]}</td>
    <td>{$value[56]}</td>
    <td>{$goods_name}</td>
    <td>{$value[57]}</td>
    <td></td>
    <td>{$value[58]}</td>
    <td></td>
  </tr>
HTML;
                }

            }


            $html .= <<<HTML
  </tbody>
</table>
</div>
HTML;


            $html .= <<<HTML

<div class="info" style="margin-top: 15px;">
  <div class="left">
    <p><strong>注释：</strong> </p>
  </div>
</div>

<table class="t1" style="width: 33%;border: 0.5px solid #000;">
  <tbody>
  <tr class="ddd">
    <td style="width: 50%;text-align: left;padding-left: 10px;">配送满意度：</td>
    <td style="width: 50%;text-align: left;">
      <div>
        <span style="display: inline-block; width: 12px;height: 12px;border: 0.5px solid #000;vertical-align: middle;"></span>
        满意
      </div>
      <div>
        <span style="display: inline-block; width: 12px;height: 12px;border: 0.5px solid #000;vertical-align: middle;"></span>
        不满意</div>
      <div>
        <span style="display: inline-block; width: 12px;height: 12px;border: 0.5px solid #000;vertical-align: middle;"></span>
        一般</div>
    </td>
  </tr>
  </tbody>
</table>
<table style="width: 33%;">
  <tbody> <tr> <td style="text-align: left;padding-left: 10px;">建议：</td></tr>
  </tbody>
</table>

<table style="width: 33%;float: left;">
  <tbody>
  <tr>
    <td style="text-align: left;padding-left: 10px;height: 20px;">旧耗材回收数量：</td>
  </tr>
  <tr >
    <td style="height: 30px; text-align: left;padding-left: 10px;">未能回收原因：</td>
  </tr>
  </tbody>
</table>

<table style="float: left; margin-left:17%;border: none;width: 200px;">
  <tbody>
  <tr style="border: none;border-bottom: 0.5px solid #000;">
    <td  style="height: 25px;text-align: left;padding-left: 10px;border: none;">签收人：</td>
  </tr>
  <tr style="border: none;border-top: 0.5px solid #000;" >
    <td style="height: 25px; text-align: left;padding-left: 10px;border: none;">签收日期：</td>
  </tr>
  </tbody>
</table>


</body>
</html>

HTML;

        }


        // 将 HTML 添加到 dompdf
        $dompdf->loadHtml($html);

// 设置页面大小和方向（可选）
        $dompdf->setPaper('A4', 'portrait');

        /**
         * //        $width = 24.109; // 宽度，单位厘米
         * //        $height = 27.950; // 高度，单位厘米
         * //
         * //// 将厘米转换为毫米
         * //        $width_mm = $width * 10 * 3 * 0.945; // 1厘米 = 10毫米
         * //        $height_mm = $height * 10 * 3 * 0.945; // 1厘米 = 10毫米
         * //
         * //// 设置页面尺寸为自定义尺寸，纵向
         * //        $dompdf->setPaper(array(0, 0, $width_mm, $height_mm), 'portrait');
         ***/

// 渲染 PDF
        $dompdf->render();

        $pdfFileName = "export/" . date('YmdHis') . Str::random(6) . "_a.pdf";

// 生成 PDF 文件名
        //$pdfFileName = '/Users/macos/Desktop/cigisped/php/public/4.pdf';

// 将 PDF 文件保存到服务器上
        $output = $dompdf->output();
        file_put_contents($pdfFileName, $output);

        //die();
        return CatchResponse::success([
//            'url'=>"http://192.168.31.168:8000" . '/' .  $pdfFileName,
//            'url'=>"http://192.168.1.8:8000" . '/' .  $file
            'url' => "http://cross.qekj.net" . '/' . $pdfFileName
        ]);
    }

    //佳壹物流其他发货单
    public function exportPDF1($id, Request $request)
    {
        $warehouseOutInfo = $this->warehouseOut->findBy($id);

        if (empty($warehouseOutInfo['edi_json'])) {
            return CatchResponse::fail('非EDI订单，不支持生成该发货单');
        }

        if ($warehouseOutInfo['status'] != 1) {
            return CatchResponse::fail('该订单未全部出库');
        }

        $customer_business_number = $warehouseOutInfo['customer_business_number'];

        // 创建一个 dompdf 对象
        $options = new Options();

        //        php load_font.php SimSun  SimSun.ttf
        $options->set('defaultFont', 'simsun'); // 设置默认字体（可选）

        $dompdf = new Dompdf($options);
        // 将 HTML 添加到 dompdf
        $html = '';

        $wareHouseOutModel = new WarehouseOutModel;
        $warehouseOutResult = $wareHouseOutModel->where(['customer_business_number' => $customer_business_number])->find()->toArray();

        $edi_json = json_decode($warehouseOutResult['edi_json'], true);

        $warehouseOutNO = $warehouseOutResult['customer_business_number'];//发货单号

        $warehouseOutDate = date("Y-m-d", strtotime($warehouseOutResult['updated_at']));//发货日期

        $providerModel = new Provider;

        $customerCode = $edi_json[0][9];//客户代码

        $customerName = $providerModel->where('account_code', $customerCode)->value('account_name');//客户名称
//        $customerCode = $edi_json[0][6];//收货方代码
//        $receiveName =  $providerModel->where('account_code',$customerCode)->value('account_name');//收货方名称

        $receiveName = $edi_json[0][19];//收货方简称
        $receiveAddress = $edi_json[0][18];//收货方地址
        $receivePerson = $edi_json[0][22];//收货方联系人
        $receivePhone = $edi_json[0][20];//收货方联系电话

        $remark = $edi_json[0][12];

        //承运人
        $carrierCode = $edi_json[0][7];//承运方代码
        $carrierName = $providerModel->where('account_code', $carrierCode)->value('account_name');//承运方名称


        $carrierType = $edi_json[0][11];//承运方式
        $carrierTypeOptions = [
            '01' => 'Truck',
            '02' => 'Mail',
            '03' => 'Rail',
            '04' => 'Sea',
            'Z1' => 'Air',
            'Z2' => 'Courier',
            'Z3' => 'Road',
            'Z4' => 'Pick up',
            'Z5' => 'To be contacted',
            'Z6' => 'Door to door deliver',
            'Z7' => 'Package',
            'Z8' => 'Express',
            'Z9' => 'Road+Railway',
        ];

        $carrierType = array_key_exists($carrierType, $carrierTypeOptions) ? $carrierTypeOptions[$carrierType] : 'Other';

        if ($warehouseOutResult['project_client'] == '202406261542166632') {//西安
            $deliveryWarehouse = '陕西省西安市幸福南路61号';
        } else {//成都
            $deliveryWarehouse = '四川成都市双流区通关路86号';
        }

//        dd($warehouseResult);

//        var_dump($edi_json);die();

        $edi_length = count($edi_json);

//        $edi_json = array_merge($edi_json,$edi_json);

        $totalNum = (int)array_sum(array_column($edi_json, 33));

        $edi_json[] = [];
        $groupArray = array_chunk($edi_json, 10);

        $pages = count($groupArray);
        $productModel = new Product;

        $logosrc = app()->getRootPath() . 'public/mnd.png';

        // 从远程 URL 获取图片内容并编码为 Base64
        $imageData = base64_encode(file_get_contents('http://cross.qekj.net/mnd.jpeg'));
        $imageBase64 = 'data:image/jpeg;base64,' . $imageData;

        //print_r($imageBase64);

        //print_r($logosrc);

        //dd($edi_json);
        for ($i = 0; $i < $pages; $i++) {
            $html .= <<<HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>发货单</title>
  <style>
    body {
      font-family: simsun;
      line-height: 1;
      font-size: 12px;
    }
    .header {
      text-align: center;
      margin-bottom: 10px;
    }
    .info {
      margin-bottom: 10px;
      clear: both; /* 清除浮动 */
    }
    .left {
      width: 40%;
      float: left;
    }
    .right {
      width: 60%;
      float: right;
      text-align: right;
    }
    .right p:first-child{
      float: left;
    }
    .info p {
      margin: 5px 0; /* 调整段落的上下边距 */
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }
    /*table, th, td {*/
    th, td {
      border: 0.5px solid black;
      padding: 2px;
      text-align: center;
    }
    table.t1 th, table.t1 td {
      border:none;
    }
    table.t1 td{
      padding: 5px 0;
    }
    th {
      /*background-color: #f2f2f2;*/
    }
    .ddd div{
      padding: 10px 0;
      clear: both; /* 清除浮动 */
    }
    .ddd div:before{
      content: '';
      display: none;
      width: 12px;
      height: 12px;
      border: 0.5px solid #000;
      float: left;
      /*margin: 0;*/
      padding: 0;
      margin-right: -12px; /* 调整打勾方框和文字之间的水平间距 */
      vertical-align: middle; /* 垂直居中对齐 */
    }
  </style>
</head>
<body>

<div class="header" style="width: 80%;height: 100px;line-height: 100px;margin: 0 auto;text-align: center;">
  <div style="float: left; width: 30%;height: 100%;text-align: left;">
<!--    <img style="height: 100%;" src="" alt=""/>-->
    <img src="{$imageBase64}"  style="height: 100%;">
  </div>
  <div style="width: 70%; vertical-align: middle; font-size: 22px;font-family: SimSun;float: left;height: 100px;line-height: 100px;">柯尼卡美能达办公系统（中国）有限公司发货单</div>
</div>
<div class="info">
  <div class="left">
    <p><strong>发货单号：</strong> {$warehouseOutNO}</p>
  </div>
  <div class="right">
    <p><strong>发货日期：</strong> {$warehouseOutDate}</p>
    <p><strong>订单创建人：</strong> EDI </p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>发货类型：</strong> </p>
  </div>
  <div class="right">
    <p><strong>订单类型：</strong> </p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>订单号：</strong> </p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>客户订单号：</strong> </p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>结算方：</strong> 发货仓库：{$deliveryWarehouse}</p>
  </div>
  <div class="right">
    <p><strong>客户名称：</strong> {$customerName}</p>
  </div>
</div>
<div class="info" style="margin: 0;">
  <div style="margin: 0;">
    <p style="margin: 0;"><strong>收货地址：</strong> {$receiveAddress}</p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>联系人：</strong> {$receivePerson}</p>
  </div>
  <div class="right">
    <p><strong>联系电话：</strong> {$receivePhone}</p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>承运人：</strong> {$carrierName}</p>
  </div>
  <div class="right">
    <p><strong>运输方式：</strong> {$carrierType}</p>
    <p><strong>客户支付运费：</strong> </p>
  </div>
</div>

<div class="info">
  <div class="left">
    <p><strong>到货日期/时间：</strong> </p>
  </div>
  <div class="right">
    <p><strong>备注：</strong> </p>
  </div>
</div>
<div class="info">
  <div class="left">
    <p><strong>当日联系人/电话：</strong> </p>
  </div>
  <div class="right">
    <p><strong>楼层数：</strong> </p>
  </div>
</div>

<div class="info">
  <div class="left">
    <p><strong>是否有货梯：</strong> </p>
  </div>
  <div class="right">
    <p><strong>停车场车高限制：</strong> </p>
  </div>
</div>

<div class="info">
  <div class="left">
    <p><strong>需要返回的物品：</strong> </p>
  </div>
  <div class="right">
    <p><strong>楼梯高度及数量：</strong> </p>
  </div>
</div>


<div class="info">
  <div class="left">
    <p><strong>是否需要现场勘查：</strong> </p>
  </div>
  <div class="right">
    <p><strong>进口门高度：</strong> </p>
  </div>
</div>


<div class="info">
  <div class="left">
    <p><strong>维护人员是否一起到现场：</strong> </p>
  </div>
  <div class="right">
    <p><strong>销售担当名称：</strong> </p>
  </div>
</div>

<div class="info">
  <div class="left">
    <p><strong>是否自提：</strong> </p>
  </div>
</div>

<div class="info" style="margin: 0;">
  <div  style="margin: 0;">
    <p style="word-wrap: break-word;padding: 0;margin: 0;">  摘要： {$remark}</p>
  </div>
</div>
HTML;

            $html .= <<<HTML
<div style="height: 20%">
<table>
  <thead>
  <tr>
    <td>序号</td>
    <td>货物编号</td>
    <td>货物名称</td>
    <td>计量单位</td>
    <td>单价</td>
    <td>数量</td>
    <td>销售额</td>
  </tr>
HTML;

            $currentPageCont = count($groupArray[$i]);
            foreach ($groupArray[$i] as $key => $value) {


                if (($i + 1 == $pages) && ($key + 1 == $currentPageCont)) {//最后一个
                    $html .= <<<HTML
  <tr>
    <td style="border: 0 !important;"></td>
    <td style="border: 0 !important;"></td>
    <td style="border: 0 !important;"></td>
    <td style="border: 0 !important;"></td>
    <td></td>
    <td>{$totalNum}</td>
    <td style="border: 0 !important;"></td>
  </tr>

HTML;

                } else {
                    $goods_name = $productModel->where('goods_name', $value[31])->value('goods_Cname');

                    $html .= <<<HTML
  <tr>
    <td>{$value[29]}</td>
    <td>{$value[31]}</td>
    <td>{$goods_name}</td>
    <td>{$value[32]}</td>
    <td></td>
    <td>{$value[33]}</td>
    <td></td>
  </tr>
HTML;
                }

            }


            $html .= <<<HTML
  </tbody>
</table>
</div>
HTML;


            $html .= <<<HTML

<div class="info" style="margin-top: 15px;">
  <div class="left">
    <p><strong>注释：</strong> </p>
  </div>
</div>

<table class="t1" style="width: 33%;border: 0.5px solid #000;">
  <tbody>
  <tr class="ddd">
    <td style="width: 50%;text-align: left;padding-left: 10px;">配送满意度：</td>
    <td style="width: 50%;text-align: left;">
      <div>
        <span style="display: inline-block; width: 12px;height: 12px;border: 0.5px solid #000;vertical-align: middle;"></span>
        满意
      </div>
      <div>
        <span style="display: inline-block; width: 12px;height: 12px;border: 0.5px solid #000;vertical-align: middle;"></span>
        不满意</div>
      <div>
        <span style="display: inline-block; width: 12px;height: 12px;border: 0.5px solid #000;vertical-align: middle;"></span>
        一般</div>
    </td>
  </tr>
  </tbody>
</table>
<table style="width: 33%;">
  <tbody> <tr> <td style="text-align: left;padding-left: 10px;">建议：</td></tr>
  </tbody>
</table>

<table style="width: 33%;float: left;">
  <tbody>
  <tr>
    <td style="text-align: left;padding-left: 10px;height: 20px;">旧耗材回收数量：</td>
  </tr>
  <tr >
    <td style="height: 30px; text-align: left;padding-left: 10px;">未能回收原因：</td>
  </tr>
  </tbody>
</table>

<table style="float: left; margin-left:17%;border: none;width: 200px;">
  <tbody>
  <tr style="border: none;border-bottom: 0.5px solid #000;">
    <td  style="height: 25px;text-align: left;padding-left: 10px;border: none;">签收人：</td>
  </tr>
  <tr style="border: none;border-top: 0.5px solid #000;" >
    <td style="height: 25px; text-align: left;padding-left: 10px;border: none;">签收日期：</td>
  </tr>
  </tbody>
</table>


</body>
</html>

HTML;

        }


        // 将 HTML 添加到 dompdf
        $dompdf->loadHtml($html);

// 设置页面大小和方向（可选）
        $dompdf->setPaper('A4', 'portrait');

        /**
         * //        $width = 24.109; // 宽度，单位厘米
         * //        $height = 27.950; // 高度，单位厘米
         * //
         * //// 将厘米转换为毫米
         * //        $width_mm = $width * 10 * 3 * 0.945; // 1厘米 = 10毫米
         * //        $height_mm = $height * 10 * 3 * 0.945; // 1厘米 = 10毫米
         * //
         * //// 设置页面尺寸为自定义尺寸，纵向
         * //        $dompdf->setPaper(array(0, 0, $width_mm, $height_mm), 'portrait');
         ***/

// 渲染 PDF
        $dompdf->render();


        $pdfFileName = "export/" . date('YmdHis') . Str::random(6) . "_a.pdf";

// 生成 PDF 文件名
        //$pdfFileName = '/Users/macos/Desktop/cigisped/php/public/4.pdf';

// 将 PDF 文件保存到服务器上
        $output = $dompdf->output();
        file_put_contents($pdfFileName, $output);

        //die();
        return CatchResponse::success([
//            'url'=>"http://192.168.31.168:8000" . '/' .  $pdfFileName,
//            'url'=>"http://192.168.1.8:8000" . '/' .  $file
            'url' => "http://cross.qekj.net" . '/' . $pdfFileName
        ]);
    }

    /**
     * 出库表单详情
     */
    public function out_detail(Request $request)
    {
        $params = $request->param();
        $data = Db::table('db_warehouse_out')
            ->alias('a')
            ->field('a.*')
            ->where('warehouse_out_id', $params['warehouse_out_id'])
            ->select()
            ->toArray();
        return CatchResponse::success($data);
    }

    //Edi物流跟踪情况表
    public function exportEdiWarehouseOut(Request $request, Excel $excel, ediWarehouseOutExport $ediExport)
    {
        return CatchResponse::success($excel->save($ediExport, 'export/edi_logistics'));
    }

    public function exportOrders(Request $request, Excel $excel, warehouseOutExport $warehouseOutExport)
    {

        return CatchResponse::success($excel->save($warehouseOutExport, 'export/warehouse_out_export'));
    }

    //批量导入
    public function importOrders(Request $request)
    {
        $file = $request->file('excelOutGoods'); // 获取上传的Excel文件
        if (!$file) {
            return CatchResponse::fail('文件未上传成功，请重试！');
        }
        $spreadsheet = IOFactory::load($file->getRealPath()); // 加载Excel文件
        $sheet = $spreadsheet->getActiveSheet(); // 获取活动工作表
        // 获取所有合并单元格
        $mergedCells = $sheet->getMergeCells();
        // 存储合并单元格的值
        $mergedValues = [];
        foreach ($mergedCells as $mergedRange) {
            $mergedValue = $sheet->rangeToArray($mergedRange)[0][0];
            $mergedValues[$mergedRange] = $mergedValue;
        }

        // 遍历所有行
        $data = [];
        foreach ($sheet->getRowIterator() as $row) {
            $rowIndex = $row->getRowIndex();
            $rowData = [];
            foreach ($sheet->getColumnIterator() as $column) {
                $colIndex = $column->getColumnIndex();
                $cellAddress = $colIndex . $rowIndex;

                // 检查是否是合并单元格
                $isMerged = false;
                $mergedValue = null;

                foreach ($mergedCells as $mergedRange) {
                    if ($sheet->getCell($cellAddress)->isInRange($mergedRange)) {
                        $isMerged = true;
                        $mergedValue = $mergedValues[$mergedRange];
                        break;
                    }
                }
                $rowData[] = $isMerged ? $mergedValue : $sheet->getCell($cellAddress)->getValue();
            }
            $data[] = $rowData;
        }

        $inGoodsData = [];
        $outGoodsData = [];
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                if (!empty($val)) {
                    if ($key > 2 && !empty($val[3]) && !empty($val[8])) {
                        $inGoodsData[] = $val;
                        $outGoodsData[$val[8]][] = $val;
                    }
                }
            }
        }

        $num = 100000000;
        // 遍历工作表数据
        $proInfo = Project::where([
            'pid' => 0,
            'tenant_id' => 10175,
            'deleted_at' => 0,
        ])->find();
        $projectId = Project::where([
            'tenant_id' => 10175,
            'deleted_at' => 0,
            'pid' => $proInfo['id']
        ])->value('project_id');
        $packInfo = Pack::where('tenant_id', 10175)->find();
        // 将数据保存到数据库
        $user = (new CatchAuth())->user();
        Db::startTrans();
        try {
            foreach ($inGoodsData as $dVal) {
                $goodsName = $dVal[3];
                $goodsType = $dVal[6];
                $goodsNumber = $dVal[4];
                $size = $dVal[5];
                $pWhere = [
                    'goods_name' => $goodsName,
                    'sku' => $goodsType,
                    'deleted_at' => 0,
                ];
                if (!empty($goodsNumber)) {
                    $pWhere['serial_number'] = $goodsNumber;
                }

                if (empty(Product::where($pWhere)->find())) {
                    $base = base_convert(uniqid(), 36, 10);
                    $idNo = date('ymdHis') . substr($base, -6);
                    $goods = [
                        "goods_name" => $goodsName,
                        "goods_Cname" => $goodsName,
                        "goods_Ename" => $goodsName,
                        "company" => "台",
                        "packing_id" => $packInfo['packing_id'] ?? '',
                        "barcode" => date('mdHis') . rand(1000, 9999),
                        "goods_id" => "JXRD" . $idNo,
                        "tenant_id" => 10175,
                        "creator_id" => 10175,
                        'created_at' => time(),
                        "sku" => $goodsType,
                        'new_carton_size' => $size,
                        'serial_number' => $goodsNumber ?? ''
                    ];
                    $gid = Product::insert($goods, 1);
                    if (!empty($gid)) {
                        //主动创建入库
                        $base = base_convert(uniqid(), 36, 10);
                        $idNo = date('ymdHis') . substr($base, -6);
                        $inData = [
                            "tenant_id" => 10175,
                            "warehousing_id" => "JXRD" . $idNo,
                            "project_id" => $proInfo['project_id'] ?? '',
                            "project_client" => $projectId ?? '',
                            "new_order_date" => date('Y-m-d', time()),
                            'warehousing_config_attribute' => '1,0',
                            'goods_number' => $num,
                            'actual_number' => $num,
                            'status' => 1,
                            "creator_id" => 10175,
                            'created_at' => time()
                        ];
                        Db::table('db_warehousing')->insert($inData);
                        $base = base_convert(uniqid(), 36, 10);
                        $idNo = date('ymdHis') . substr($base, -6);
                        $orderGoods = [
                            "batch_number" => 'p' . date('mdHis') . rand(1000, 9999),
                            //"pallet_no" => 'P' . date('mdHis') . rand(1000, 9999),
                            "creator_id" => 10175,
                            "enter_type" => 1,
                            "goods_id" => $goods['goods_id'],
                            "goods_name" => $goods["goods_name"],
                            "number" => $num,
                            "packing_id" => $packInfo['packing_id'],
                            "tenant_id" => 10175,
                            "type" => "add",
                            'actual_number' => $num,
                            'status' => 1,
                            'created_at' => time(),
                            "warehousing_id" => $inData['warehousing_id'],
                            "warehousing_son_config_attribute" => "1,9545",
                            "warehousing_son_id" => $idNo
                        ];
                        $params = (new SyncGoods())->goods_info($orderGoods);
                        $trayBoxNum = (new Pack)->getTrayBoxNum($params['data']['number'], $params['data']['packing_id']);
                        $params['data']['tray_number'] = $trayBoxNum['tray_num'];
                        $params['data']['box_number'] = $trayBoxNum['box_num'];
                        $params['data']['specification'] = $packInfo['packing_num'] . ' / ' . $packInfo['unit_name'] . " /" . $packInfo['layup_num'];
                        $sonId = Db::table('db_warehousing_son')->insert($params['data'], true);
                        $trayId = (new SyncGoods())->inGoods($params['data'], $packInfo);
                        $stockId = (new SyncGoods())->in($trayId, $params['data'], $inData, $packInfo);
                        $logId = (new SyncGoods())->inLog($stockId, $params['data'], $packInfo);
                    }
                }
            }
            foreach ($outGoodsData as $oVal) {
                $relationName = $oVal[0][8];
                $relationPhone = $oVal[0][9];
                $addr = $oVal[0][10];
                $client = [
                    "role" => "10,11",
                    "account_code" => "JXRD",
                    "account_name" => $oVal[0][2],
                    "account_key" => $oVal[0][2],
                    "relation_name" => $relationName,
                    "relation_phone" => $relationPhone,
                    "addr" => $addr,
                    "creator_id" => $user['tenant_id'],
                    "tenant_id" => $user['tenant_id'],
                ];
                $sNubmer = '';
                if (empty($pInfo = Provider::where([
                    'account_name' => $client['account_name'],
                    'relation_name' => $client['relation_name'],
                    'relation_phone' => $client['relation_phone'],
                ])->find())) {
                    $pid = (new Provider())->insert($client, 1);
                    $sNubmer = "C" . str_pad($pid, 5, '0', STR_PAD_LEFT);
                    (new Provider())->where('id', $pid)->update(["serial_number" => $sNubmer]);
                } else {
                    $sNubmer = $pInfo['serial_number'];
                }

                $base = base_convert(uniqid(), 36, 10);
                $idNo = date('ymdHis') . substr($base, -6);
                $masterOrder = [
                    "creator_id" => $user['tenant_id'],
                    "support_export" => 1,
                    "project_id" => $proInfo['project_id'] ?? '',
                    "project_client" => $projectId ?? '',
                    "transport_type" => "陆运",
                    "ship_to" => $client['account_name'],
                    "ship_to_name" => $relationName,
                    "ship_to_phone" => $relationPhone,
                    "ship_to_address" => $addr,
                    "consignee_serial_number" => $sNubmer,
                    "consignee_relation_name" => $client['account_name'],
                    "consignee_relation_phone" => $client['relation_phone'],
                    "consignee_addr" => $client['addr'],
                    "goods_number" => 0,
                    "new_order_date" => date('Y-m-d'),
                    "tenant_id" => $user['tenant_id'],
                    "warehouse_out_id" => "JXRD" . $idNo,
                    "created_at" => time()
                ];
                $outId = (new WarehouseOutModel())->insert($masterOrder, 1);
                $masterOrder['packing_id'] = $packInfo['packing_id'];
                $res = self::orderGoods($masterOrder, $oVal);
                (new WarehouseOutModel())->where(['id' => $outId])->update(["goods_number" => $res]);
            }
            Db::commit();
            return CatchResponse::success();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('失败' . $exception->getMessage());
        }
    }

    public
    static function orderGoods($masterOrder, $goods)
    {
        $outNum = 0;
        foreach ($goods as $gVal) {
            $goodsName = $gVal[3];
            $goodsType = $gVal[6];
            $outNum += $gVal[7];
            $goodsNumber = $gVal[4];
            $pWhere = [
                'goods_name' => $goodsName,
                'sku' => $goodsType,
                'deleted_at' => 0,
            ];
            if (!empty($goodsNumber)) {
                $pWhere['serial_number'] = $goodsNumber;
            }
            $goodsInfo = Product::where($pWhere)->find();
            $base = base_convert(uniqid(), 36, 10);
            $idNo = date('ymdHis') . substr($base, -6);
            $params = [];
            $params['box_number'] = $gVal[7];
            $params['number'] = $gVal[7];
            $params['warehouse_out_id'] = $masterOrder['warehouse_out_id'];
            $params['tenant_id'] = $masterOrder['tenant_id'];
            $params['goods_name'] = $goodsInfo['goods_name'];
            $params['goods_id'] = $goodsInfo['goods_id'];
            $params['packing_id'] = $masterOrder['packing_id'];
            $params['warehouse_out_son_id'] = $idNo;
            $where = [];
            $where['project_client'] = $masterOrder['project_client'];
            $where['goods_id'] = $goodsInfo['goods_id'];
            $where['packing_id'] = $masterOrder['packing_id'];
            $stock_number = DB::name('db_stock')
                ->field('SUM(number) as number')
                ->where($where)
                ->where('deleted_at', 0)
                ->find();
            $params['stock_number'] = (int)$stock_number['number'];
            $params['packing_num'] = 1;
            $params['unit_name'] = '台';
            //出库筛选
            (new WarehouseOutSonModel())->storeBy($params);
        }
        return $outNum;
    }

    public function downloadFile(Request $request){
         return CatchResponse::success(download(public_path().'/出库导入数据模板.xlsx','file.xlsx'));
    }
}